package com.definity.toolkit.web.taglib;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import com.definity.toolkit.message.Message;
import com.definity.toolkit.message.MessageType;

public class MessageBoxTag extends BaseTag {

	private static final long serialVersionUID = -7184770242677139818L;

	public MessageBoxTag() {
		
	}

	@Override
	public int doStartTag() throws JspException {
		return SKIP_BODY;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public int doEndTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		
		StringBuilder builder = new StringBuilder();

		List<Message> messages = (List<Message>) request.getAttribute("messages");
		if (messages != null && !messages.isEmpty()) {
			String messageTypeClass = getMessageTypeClass(messages.get(0).getMessageType());
			builder.append("<ul class=\"");
			builder.append("messagebox ");
			builder.append(messageTypeClass);
			builder.append("\">");

			for (Message message : messages) {
				builder.append("<li>");
				builder.append(message.getMessage());
				builder.append("</li>");
			}

			builder.append("</ul>");
		} else {
			builder.append("<ul class=\"messagebox\"></ul>");
		}
		
		write(builder);
		
		return EVAL_PAGE;
	}

	private String getMessageTypeClass(MessageType messageType) {
		return messageType.name().toLowerCase();
	}
	
}
